Imports Aricie.DNN.Modules.LuceneSearch.Business
Imports Aricie.DNN.Modules.LuceneSearch.Logs
Imports Lucene.Net.Index
Imports Lucene.Net.Search

Namespace Aricie.DNN.Modules.LuceneSearch.UI

    Public MustInherit Class FieldFilterBase
        Inherits LuceneFilterControlBase

        Private Shared DefaultFieldName As String = String.Join(";", New String() {DnnSearchItemField.Content, DnnSearchItemField.Title})

        Private _FieldName As String = DefaultFieldName
        Private _FieldNames As IEnumerable(Of String)

        Public Property FieldName() As String
            Get
                Return _FieldName
            End Get
            Set(ByVal value As String)
                _FieldName = value
            End Set
        End Property

#Region "Overrides"

        Public Overrides Function GetFilterLogElement() As Logs.FilterLogElement
            Return New FilterLogElement(Me.GetType.Name & ":" & Me.FieldName, Me.FieldValue)
        End Function

#End Region


#Region "ILuceneFilterControl implementation"



        Public Overrides Function GetFieldNames() As IEnumerable(Of String)
            If _FieldNames Is Nothing Then
                _FieldNames = FieldName.Split((";"c))
            End If
            Return _FieldNames
        End Function

        Public Overrides Function HasFilter() As Boolean
            Return Me.FieldValue <> ""
        End Function

        Public Overrides Function GetFilter() As LuceneFilterQuery
            Dim toReturn As New LuceneFilterQuery
            Dim fieldFilter As TermQuery = Nothing

            Dim fieldValue As String = Me.FieldValue
            If Not fieldValue = "" Then
                Dim fieldTerm As New Term(FieldName, fieldValue)
                fieldFilter = New TermQuery(fieldTerm)
            End If
            toReturn.FilterQuery = fieldFilter
            Return toReturn
        End Function



        Public Overrides Function ParseFilter(ByVal objFilter As LuceneFilterQuery) As Boolean
            If TypeOf (objFilter.FilterQuery) Is TermQuery Then
                Dim objTerm As Term = DirectCast(objFilter.FilterQuery, TermQuery).Term()
                If objTerm.Field = Me.FieldName Then
                    Dim fieldValue As String = BusinessController.GetTermText(objTerm)
                    Me.FieldValue = fieldValue
                    Return True
                End If
            End If
            Return False
        End Function

#End Region


        Protected MustOverride Property FieldValue() As String

        Public Property Field() As String
            Get
                Return Me.FieldValue
            End Get
            Set(ByVal value As String)
                Me.FieldValue = value
            End Set
        End Property

    End Class
End Namespace